package tech.yunland.shop.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.w3c.dom.Document;

/**
 * word 转换成html
 * 李珂<likenamehaojie@hotmail.com>
 */
public class ConvertUtil {
   
	
	public static void main(String [] args){
		String filePath = "/home/yunland03/a/";
		String from = "2.doc";
		String to = "nide1.html";
		String a = 	ConvertUtil.ConvertToHtml(filePath, from, to);
		System.out.print(a);
	}

	
	/**
	 * 
	 * @param filePath   文件路径
	 * @param from       文件名称
	 * @param to         文件转换后的名字
	 * @return           如果成功返回文件地址 否则返回 空串
	 */
	public static String ConvertToHtml(String filePath,String from ,String to){
		try{
		if(from.endsWith(".docx")){
			Word2007ToHtml(filePath, from, to);
		}else if(from.endsWith(".doc")){
			Word2003ToHtml(filePath, "image", from, to);
		}else{
			HSSFWorkbook hw = new HSSFWorkbook();
			String file  = filePath+from;
			InputStream in = new FileInputStream(file);
			POIFSFileSystem  fs = new POIFSFileSystem(in);
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			StringBuffer content = ExcelShower.excleToHtml(wb, null, "to", null, 0);
			return content.toString();
		}
		}catch (IOException e) {
			e.printStackTrace();
			  return "";
			// TODO: handle exception
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return filePath+from;
	}
	
	
    /**
     * 2007版本word转换成html
     * @throws IOException
     */
    private static String Word2007ToHtml(String filepath,String oName ,String tName) throws IOException {
    /*    String filepath = "d:/";
        String fileName = "2.docx";
        String htmlName = "滕王阁序2007.html";*/
    	ByteArrayOutputStream baos = null;
       try{
    	final String file = filepath + oName;
        File f = new File(file);  
        if (!f.exists()) {  
            System.out.println("Sorry File does not Exists!");  
        } else {  
            if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {  
                  
                // 1) 加载word文档生成 XWPFDocument对象  
                InputStream in = new FileInputStream(f);  
                XWPFDocument document = new XWPFDocument(in);  
  
                // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
                File imageFolderFile = new File(filepath);  
                XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
                options.setExtractor(new FileImageExtractor(imageFolderFile));
                options.setIgnoreStylesIfUnused(false);  
                options.setFragment(true);  
                  
                // 3) 将 XWPFDocument转换成XHTML  
                OutputStream out = new FileOutputStream(new File(filepath + tName));  
                XHTMLConverter.getInstance().convert(document, out, options);
               
                //也可以使用字符数组流获取解析的内容
                 baos  = new ByteArrayOutputStream(); 
                  XHTMLConverter.getInstance().convert(document, baos, options);  
                  String content = baos.toString();
                  System.out.println(content);
                 
                  return content;
            } else {  
                System.out.println("Enter only MS Office 2007+ files");  
                return "";
            } 
        }  
       }finally{
    	   if(baos!=null){
    		   baos.close();
    	   }
       }
	return "";
    }  
    
    /**
     * /**
     * 2003版本word转换成html
     * @throws IOException   doc
     * @throws TransformerException
     * @throws ParserConfigurationException
     */
    private static  String Word2003ToHtml(String filepath,String imageDir,String oName,String toName) throws IOException, TransformerException, ParserConfigurationException {
/*        String filepath = "d:/";
        final String imagepath = "d:/image/";
        String fileName = "2.doc";
        String htmlName = "22.html";*/
    	final String imagepath = filepath +imageDir +"/";
        final String file = filepath + oName;
        InputStream input = new FileInputStream(new File(file));
        HWPFDocument wordDocument = new HWPFDocument(input);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        //设置图片存放的位置
        wordToHtmlConverter.setPicturesManager(new PicturesManager() {

            @Override
            public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                File imgPath = new File(imagepath);
                if(!imgPath.exists()){//图片目录不存在则创建
                    imgPath.mkdirs();
                }
                File file = new File(imagepath + suggestedName);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(content);
                    os.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return imagepath + suggestedName;
            }
        });
        
        //解析word文档
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();
        
/*        File htmlFile = new File(filepath + toName);
        OutputStream outStream = new FileOutputStream(htmlFile);*/
        
        //也可以使用字符数组流获取解析的内容
          ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
          OutputStream outStream = new BufferedOutputStream(baos);

        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(outStream);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer serializer = factory.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        
        serializer.transform(domSource, streamResult);

        //也可以使用字符数组流获取解析的内容
         String content = baos.toString();
         System.out.println(content);
         baos.close();
        outStream.close();
        return content;
    }
}